import { Effect, ImmerReducer, Reducer, Subscription } from 'umi';
import {getUserList,editUserList,delUserList,addUserList} from "../service/user"
import {singleType} from '../data.d'
interface UserModelType{
  namespace:string,
  state:stateType,
  effects:{
    getUserList:Effect,
    editUserList:Effect,
    delUserList:Effect,
    addUserList:Effect,
  },
  reducers:{
    saveUserList:Reducer<stateType>
  },
  subscriptions:{
    setup:Subscription
  }
}
export interface stateType{
  dataSource:singleType[]
}

const UserModel:UserModelType = {
  namespace: 'users',
  state: {
    dataSource:[],
  },

  effects: {
    *getUserList({ payload }, { call, put }) {
      const dataSource = yield call(getUserList,payload)
      yield put({
        type:'saveUserList',
        payload:{
          dataSource
        }
      })
    },
    *editUserList({ payload,callback }, { call, put }) {
      
      const res = yield call(editUserList,payload);
      yield put({
        type:'getUserList',
      })
      yield callback(res)
    },
    *delUserList({ payload,callback }, { call, put }) {
      const delInfo = yield call(delUserList,payload)
      yield put({
        type:'getUserList',
      })
      yield callback(delInfo)
    },
    *addUserList({ payload,callback }, { call, put }) {
      const res = yield call(addUserList,payload)
      yield put({
        type:'getUserList',
      })
      yield callback(res)
    },
  },
  reducers: {
    saveUserList(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname}) => {
        if (pathname === '/user') {
          dispatch({
            type: 'getUserList',
            payload:{
              id:123,
              age:27
            }
          })
        }
      });
    }
  }
};

export default UserModel;